package com.corot.codoc.service.impl;

import com.corot.codoc.bean.Content;
import com.corot.codoc.bean.Segment;
import com.corot.codoc.dao.ContentDao;
import com.corot.codoc.dao.SegmentDao;
import com.corot.codoc.exception.DataException;
import com.corot.codoc.exception.ParamException;
import com.corot.codoc.service.ContentService;
import com.corot.core.model.entity.BaseEntity;
import com.corot.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;

/**
 * 类的描述
 *
 * @author leesir
 */
@Service
@Transactional
public class ContentServiceImpl implements ContentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContentServiceImpl.class);

    @Autowired
    private ContentDao contentDao;

    @Autowired
    private SegmentDao segmentDao;


    @Override
    public void createContent(String contentHtml, Integer segmentId) throws InvocationTargetException, IllegalAccessException {
        if(valid(contentHtml,segmentId)){
            Segment segment = segmentDao.get(segmentId);
            Content content = new Content();
            content.setHtml(contentHtml);
            content.setSegment(segment);
            contentDao.save(content);
        }
    }

    private boolean valid(String content, Integer segmentId) {
        if(segmentId==null){
            throw new ParamException("创建内容时，章节不能为空");
        }else {
            Segment segment = segmentDao.get(segmentId);
            if(segment==null|| BaseEntity.DEL_FLAG_DELETE.equals(segment.getDelFlag())){
                throw new DataException("章节无效");
            }else if(StringUtils.isBlank(content)){
                LOGGER.info("章节内容为空[segmentId:+"+segmentId+"]");
            }
        }
        return true;
    }

    @Override
    public Content getContentBySegmentId(Integer segmentId) {
        return contentDao.getContentBySegmentId(segmentId);
    }
}
